package com.example.demo.mvvm.net;

import com.example.demo.mvvm.utils.AppCacheSharedPreferences;

import java.io.IOException;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 80711 on 2018/5/22.
 */

public class CookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //先判断本地是否含有缓存的cookies信息
        Request request = chain.request().newBuilder()
                .addHeader("Cookie", AppCacheSharedPreferences.getCacheString("Cookie")).build();

        Response resp = chain.proceed(request);


        List<String> cookies = resp.headers("set-cookie");
        String cookieStr = "";
        if (cookies != null && cookies.size() > 0) {
            if (request.url().toString().contains("user/login") || request.url().toString().contains("user/register")) {
                for (String str : cookies) {
                    cookieStr += str;
                }
                AppCacheSharedPreferences.putCacheString("Cookie", cookieStr);
            }
        }

        return resp;
    }

}
